package pyf.demo13;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author pengyifeng
 * @version 5.1
 * @ClassName LockDemo.java
 * @Description 显示锁Lock用法
 * @createTime 2021年07月27日 14:17:00
 */
public class LockDemo {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();
        new Thread(buyTicket, "黄牛").start();
        new Thread(buyTicket, "小明").start();
        new Thread(buyTicket, "小红").start();
    }

    static class BuyTicket implements Runnable {

        int num = 10;
        boolean flag = true;
        ReentrantLock lock = new ReentrantLock();

        private void buy() {
            //模拟延时
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (num > 0) {
                System.out.println(Thread.currentThread().getName() + "购买票成功第" + num-- + "张票");
            } else {
                flag = false;
                return;
            }

        }

        @Override
        public void run() {
            while (flag) {
                try {
                    lock.lock();
                    buy();
                } finally {
                    lock.unlock();

                }

            }
        }
    }
}
